package com.lxq.LeetCode.mergeTwoLists;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public static void main(String[] args) {

    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        ListNode head = new ListNode(0, null);
        ListNode pHead = head;
        ListNode p1 = list1;
        ListNode p2 = list2;
        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                pHead.next = p1;
                do {
                    p1 = p1.next;
                    pHead = pHead.next;
                } while (p1 != null && p1.val == pHead.val);
            } else {
                pHead.next = p2;
                do {
                    p2 = p2.next;
                    pHead = pHead.next;
                } while (p2 != null && p2.val == pHead.val);
            }
        }
        if (p1 == null && p2 != null) {
            pHead.next = p2;
        }else if (p2 == null && p1 != null) {
            pHead.next = p1;
        }

        return head.next;
    }
}
